<?php
include "config.php";
//Entrada
$fundo = intval($_GET['fundo']);
$raio = intval($_GET['raio']);
$tipo = intval($_GET['tipo']);
$comMapa = intval($_GET['comMapa']);
//Constantes
$DIM_Width = 600;
$DIM_Height = 356;

    function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){ 
        // creating a cut resource 
        $cut = imagecreatetruecolor($src_w, $src_h); 

        // copying relevant section from background to the cut resource 
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h); 
        
        // copying relevant section from watermark to the cut resource 
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h); 
        
        // insert cut resource to destination image 
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct); 
    }
//Minha implementacao do circulo, nao tava conseguindo fazer um overlap de alpha entre eles na implementacao normal do php
function doCircle($image, $cX, $cY, $raio) {
	global $qtd,$fundo;
	for ($X=-1*$raio; $X<=$raio; $X++) {
		for ($Y=-1*$raio; $Y<=$raio; $Y++) {
			//Se o pixel faz parte do circulo
			if (pow($X,2)+pow($Y,2) <= pow($raio,2)) {
				if ($qtd[$X+$cX][$Y+$cY]+1 < $fundo)
					$qtd[$X+$cX][$Y+$cY]++;
			}
		}
	}
}
function writeCircles() {
	global $image, $qtd, $fundo;
	foreach ($qtd as $X => $value) {
		foreach ($value as $Y => $value) {
			//echo "qtd[$X][$Y] = ".$qtd[$X][$Y]."<BR>";
			$alpha=127-($qtd[$X][$Y]/$fundo)*127;
			$cor = imagecolorallocatealpha($image,255,0,0,$alpha);
			imagesetpixel($image,$X,$Y,$cor);
		}
	}
}

//Codigo
if ($comMapa==1)
	$mapa = imagecreatefromjpeg("mapa_barao2.jpg");
else
	$mapa = imagecreatetruecolor($DIM_Width,$DIM_Height);
$image=imagecreatetruecolor($DIM_Width,$DIM_Height);
imagealphablending($image, false);
imagesavealpha($image, true);
$branco=imagecolorallocatealpha($image,255,255,255,127);
imagefill($image,0,0,$branco);
//Faz o SQL
$SQL = "SELECT ID,X,Y FROM caso";
if ($tipo>0) {
	$SQL .= " WHERE tipo = ".$tipo;
}
$alpha = round(127-(1/$fundo)*127);
//$cor = imagecolorallocatealpha($image,255,0,0,$alpha);
$rs = mysql_query($SQL, $conexao);
while ($line = mysql_fetch_array($rs)) {
//	imagefilledellipse($image,$line['X'],$line['Y'],$raio*2,$raio*2,$cor);
	doCircle($image,$line['X'],$line['Y'],$raio);
}
writeCircles();

header('Content-type: image/png'); 
if ($comMapa==1) {
	imagealphablending($image, true);
	imagesavealpha($image, false);
	imagecopymerge_alpha($mapa,$image,0,0,0,0,$DIM_Width,$DIM_Height,100);
	imagepng($mapa);
} else {
	imagepng($image);
}
?>